package com.itheima.project.config;

import com.itheima.project.constant.AppletCacheConstant;
import com.itheima.project.pojo.Dish;
import com.itheima.project.service.IDishService;
import org.redisson.api.RAtomicLong;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * @ClassName InitDish.java
 * @Description 初始化菜品库存
 */
@Component
public class InitDish {

    @Autowired
    IDishService dishService;

    @Autowired
    RedissonClient redissonClient;

    @Async   // 开启异步线程执行
    @PostConstruct  // 当前类被实例化后执行该注解对应的方法
    public void initDataDict(){
        Timer timer = new Timer();
        // 延迟10s 执行该任务
        timer.schedule(new InitTask(timer),10*1000);
    }


    class InitTask extends TimerTask {

        private Timer timer;

        private InitTask(Timer timer) {
            this.timer= timer;
        }

        @Override
        public void run() {
            //查询所有有效的且起售状态的菜品
            List<Dish> dishList = dishService.findDishVos();
            for (Dish dish : dishList) {
                //构建初始化库存
                String key = AppletCacheConstant.REPERTORY_DISH+dish.getId();
                RAtomicLong atomicLong = redissonClient.getAtomicLong(key);
                atomicLong.set(dish.getDishNumber());
            }
        }
    }

}
